package cn.tedu._07vehicle.base.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;

@Slf4j
public class TimeAccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入到限定访问时间的拦截器...");
        /*
        1.获取当前时间
        2.判断是否在06:00-23:00之间;
          2.1是,return true放行;
          2.2否,return false拦截;
         */
        LocalDateTime now = LocalDateTime.now();
        int hour=now.getHour();
        if (hour<6||hour>22) {
            //不允许访问
            //方案1:抛出异常,并在全局异常处理器中处理该异常;
          //  throw new RuntimeException("非常抱歉,只能在06:-23:00之间进行访问");
            //方案2:重定向到一个错误页面("/error.html")
            response.sendRedirect("/error.html");
            return false;

        }else {//允许访问
            return true;//放行
        }
    }
}
